<template>
  <div class="course-review-list">
    <el-card class="review-card">
      <template #header>
        <div class="card-header">
          <span>课程评价管理</span>
          <div class="header-actions">
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入课程名称"
              style="width: 300px; margin-right: 10px"
              clearable
              :maxlength="200"
              @clear="handleSearch"
              @keydown.enter="handleSearch"
            >
              <template #append>
                <el-button icon="Search" @click="handleSearch" :loading="loading" />
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <el-table
        :data="reviewList"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="course.name" label="课程名称" show-overflow-tooltip />
        <el-table-column prop="user.name" label="评价用户" width="120" />
        <el-table-column prop="rating" label="评分" width="100">
          <template #default="scope">
            <el-rate
              v-model="scope.row.rating"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}星"
            />
          </template>
        </el-table-column>
        <el-table-column prop="content" label="评价内容" show-overflow-tooltip />
        <el-table-column prop="helpfulCount" label="有用数" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ formatStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="评价时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button
              size="small"
              type="success"
              @click="handleApprove(scope.row)"
              v-if="scope.row.status === 'PENDING'"
            >
              通过
            </el-button>
            <el-button
              size="small"
              type="warning"
              @click="handleReject(scope.row)"
              v-if="scope.row.status === 'PENDING'"
            >
              拒绝
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleHide(scope.row)"
              v-if="scope.row.status === 'APPROVED'"
            >
              隐藏
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 查看评价详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="评价详情"
      width="800px"
    >
      <div class="review-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="课程ID">{{ currentReview.courseId }}</el-descriptions-item>
          <el-descriptions-item label="用户">{{ currentReview.user?.name }}</el-descriptions-item>
          <el-descriptions-item label="评分">
            <el-rate
              v-model="currentReview.rating"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}星"
            />
          </el-descriptions-item>
          <el-descriptions-item label="内容">{{ currentReview.content }}</el-descriptions-item>
          <el-descriptions-item label="标签">
            <el-tag
              v-for="tag in currentReview.tags"
              :key="tag"
              style="margin-right: 10px; margin-bottom: 10px;"
            >
              {{ tag }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="图片" v-if="currentReview.images && currentReview.images.length > 0">
            <div class="review-images">
              <el-image
                v-for="image in currentReview.images"
                :key="image"
                :src="image"
                :preview-src-list="currentReview.images"
                :initial-index="currentReview.images.indexOf(image)"
                style="width: 100px; height: 100px; margin-right: 10px; margin-bottom: 10px;"
              />
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="匿名">{{ currentReview.isAnonymous ? '是' : '否' }}</el-descriptions-item>
          <el-descriptions-item label="精选">{{ currentReview.isFeatured ? '是' : '否' }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ formatStatus(currentReview.status) }}</el-descriptions-item>
          <el-descriptions-item label="评价时间">{{ currentReview.createdAt }}</el-descriptions-item>
        </el-descriptions>

        <div class="review-replies" v-if="currentReview.replies && currentReview.replies.length > 0">
          <h4>回复内容</h4>
          <div
            v-for="reply in currentReview.replies"
            :key="reply.id"
            class="reply-item"
          >
            <div class="reply-header">
              <span class="reply-user">{{ reply.userType === 'ADMIN' ? '管理员' : reply.userType === 'COACH' ? '教练' : '用户' }}</span>
              <span class="reply-time">{{ reply.createdAt }}</span>
            </div>
            <div class="reply-content">{{ reply.content }}</div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { CourseReview } from '@/types/api/review'
import { courseReviewApi, reviewManagementApi } from '@/api/modules/review'
import { formUtils } from '@/utils'

// 表格相关
const loading = ref(false)
const reviewList = ref<CourseReview[]>([])
const currentReview = ref<CourseReview>({
  id: 0,
  courseId: 0,
  userId: 0,
  user: {
    id: 0,
    name: '',
    avatar: ''
  },
  rating: 0,
  content: '',
  images: [],
  tags: [],
  isAnonymous: false,
  isFeatured: false,
  helpfulCount: 0,
  isHelpful: false,
  status: 'PENDING',
  createdAt: '',
  replies: []
})

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 分页相关
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const detailDialogVisible = ref(false)

// 获取评价列表
const getReviewList = async () => {
  try {
    loading.value = true
    // 这里需要根据实际接口调整，暂时使用模拟数据
    // const res = await courseReviewApi.getCourseReviewList(courseId, {
    //   page: pagination.page,
    //   pageSize: pagination.pageSize
    // })

    // 模拟数据
    reviewList.value = [
      {
        id: 1,
        courseId: 1,
        userId: 1,
        user: {
          id: 1,
          name: '张三',
          avatar: ''
        },
        rating: 5,
        content: '课程非常棒，教练很专业！',
        images: [],
        tags: ['专业', '耐心'],
        isAnonymous: false,
        isFeatured: false,
        helpfulCount: 15,
        isHelpful: false,
        status: 'APPROVED',
        createdAt: '2025-10-25T18:30:00Z',
        replies: []
      }
    ]
    pagination.total = 1
  } catch (error) {
    ElMessage.error('获取评价列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getReviewList()
}

// 刷新列表
const refreshList = () => {
  getReviewList()
}

// 查看评价详情
const handleView = (row: CourseReview) => {
  currentReview.value = row
  detailDialogVisible.value = true
}

// 通过评价
const handleApprove = async (row: CourseReview) => {
  formUtils.handleDeleteConfirm('这条评价', async () => {
    await reviewManagementApi.auditReview(row.id, {
      status: 'APPROVED'
    })
    refreshList()
  }, {
    title: '提示',
    successMessage: '操作成功',
    errorMessage: '操作失败'
  })
}

// 拒绝评价
const handleReject = async (row: CourseReview) => {
  try {
    const { value } = await ElMessageBox.prompt('请输入拒绝原因', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /^.{1,200}$/,
      inputErrorMessage: '拒绝原因长度应在1-200个字符之间'
    })

    await reviewManagementApi.auditReview(row.id, {
      status: 'REJECTED',
      rejectReason: value
    })
    ElMessage.success('操作成功')
    refreshList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 隐藏评价
const handleHide = async (row: CourseReview) => {
  formUtils.handleDeleteConfirm('这条评价', async () => {
    await reviewManagementApi.hideReview(row.id, true)
    refreshList()
  }, {
    title: '提示',
    successMessage: '操作成功',
    errorMessage: '操作失败'
  })
}

// 分页相关方法
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  getReviewList()
}

const handleCurrentChange = (val: number) => {
  pagination.page = val
  getReviewList()
}

// 格式化状态
const formatStatus = (status: string) => {
  const statusMap: Record<string, string> = {
    'PENDING': '待审核',
    'APPROVED': '已通过',
    'REJECTED': '已拒绝',
    'HIDDEN': '已隐藏'
  }
  return statusMap[status] || status
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    'PENDING': 'warning',
    'APPROVED': 'success',
    'REJECTED': 'danger',
    'HIDDEN': 'info'
  }
  return typeMap[status] || 'info'
}

// 生命周期
onMounted(() => {
  getReviewList()
})
</script>

<style scoped>
.course-review-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.review-images {
  display: flex;
  flex-wrap: wrap;
}

.reply-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 10px;
}

.reply-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}

.reply-user {
  font-weight: bold;
  color: #409eff;
}

.reply-time {
  font-size: 12px;
  color: #909399;
}

.reply-content {
  line-height: 1.5;
}
</style>
